using System;
using System.IO;
using System.Reflection;
using System.Web;
using NWrapper.Attributes;

namespace NWrapper
{
	public static class ProxyHelper
	{
		public static T GetObject<T>(string assemblyName, string className)
		{
			if (HttpContext.Current != null)
			{
				assemblyName = Path.Combine(HttpRuntime.BinDirectory, assemblyName);
			}
			if (!assemblyName.EndsWith(".dll"))
			{
				assemblyName += ".dll";
			}

			Assembly assembly = Assembly.LoadFrom(assemblyName);
			if (assembly == null)
				throw new NWrapperException("Unable to load assembly " + assemblyName);

			Type type = assembly.GetType(className);
			if (type == null)
				throw new NWrapperException("Unable to load type " + className);

			if (type.GetCustomAttributes(typeof(SingletonAttribute), false).Length != 0)
			{
				PropertyInfo prop = type.GetProperty("Instance");
				if (prop == null)
					throw new NWrapperException("Static property 'Instance' does not exist on type " + className);

				object obj = prop.GetValue(null, null);
				if (obj is T)
					return (T)obj;
				else
					throw new NWrapperException("Unable to get value for static property 'Instance' of type " + className);
			}
			else
			{
				object instance = assembly.CreateInstance(className);
				if (instance is T)
					return (T)instance;
				else
					throw new NWrapperException("Unable to create an instance of " + className);
			}
		}
	}
}
